from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth import logout, login, authenticate
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import password_change, password_change_done
from django.db import models
from profile.models import ProfileImage, UserProfile
from profile.forms import UploadProfilePhotoForm, EditProfileInfoForm
from datetime import datetime
from common import globalvars
import urllib, re, settings

def GetUser(user_name):
    try:
        return User.objects.get(username=user_name)
    except User.DoesNotExist:
        raise Http404('Requested user not found.')

def GetDefaultImageUrl(user):
    if user.profileimage_set.count() > 0:
        media_url = user.profileimage_set.order_by('modified_date').reverse()[0].mediumdisplay.url
    else:
        media_url = globalvars.GetGenericAvatarImgURL()
    return media_url

@login_required
def profile(request, user_name):
    user = GetUser(user_name)
    review_dict = []
    # match the dish with the dishimage
    dish_imgs = user.dishimage_set.all()
    reviews = user.review_set.all()
    for review in reviews:
        try:
            img_url = dish_imgs.filter(dish=review.dish)[0].thumbnail.url
            review_dict.append((review, img_url))
        except:
            review_dict.append((review, globalvars.GetGenericFoodImgURL()))
    variables = RequestContext(request, {
        'user_public' : user,
		'profile' : user.get_profile(),
        'media_url' : GetDefaultImageUrl(user),
		'review_dict' : review_dict,
    })
    return render_to_response('profile/profile.html', variables)

@login_required
def edit_profile(request, user_name):
    if request.method == 'POST':
        form = EditProfileInfoForm(request.POST)
        if form.is_valid():
            userprofile = UserProfile.objects.get(user=request.user)
            if form.cleaned_data['location'] != "":
                userprofile.location = form.cleaned_data['location']
            if form.cleaned_data['website'] != "":
			    userprofile.website = form.cleaned_data['website']
            userprofile.save()
            return HttpResponseRedirect('/user/' + user_name)
    else:
        form = EditProfileInfoForm()
    user = GetUser(user_name)
    variables = RequestContext(request, {
        'user_public' : user,
        'media_url' : GetDefaultImageUrl(user),
    })
    return render_to_response('profile/profile_edit.html', {'form': form}, context_instance=variables)
	
@login_required
def upload_photo(request, user_name):
    if request.method == 'POST':
        form = UploadProfilePhotoForm(request.POST, request.FILES)
        if form.is_valid():
            new_profile_image = form.save(commit=False)
            new_profile_image.name = user_name
            new_profile_image.isPrimary = True
            new_profile_image.user = request.user
            new_profile_image.save()
            return HttpResponseRedirect('/user/' + user_name)
    else:
        form = UploadProfilePhotoForm()
    variables = RequestContext(request, {
        'media_url' : GetDefaultImageUrl(GetUser(user_name)),
    })
    return render_to_response('profile/profilepic.html', {'form': form}, context_instance=variables)
	
@login_required
def change_photo(request, user_name, profileimg_id):
    try:
        user = User.objects.get(username=user_name)
    except User.DoesNotExist:
        raise Http404('Requested user not found.')
    img = user.profileimage_set.get(pk=profileimg_id)
    img.modified_date = datetime.now()
    img.save()
    variables = RequestContext(request, {
        'user_public' : user,
        'media_url' : GetDefaultImageUrl(user),
    })
    return HttpResponseRedirect('/user/' + user_name)

@login_required
def delete_photo(request, user_name, profileimg_id):
    try:
        user = User.objects.get(username=user_name)
    except User.DoesNotExist:
        raise Http404('Requested user not found.')
    user.profileimage_set.get(pk=profileimg_id).delete()
    variables = RequestContext(request, {
        'user_public' : user,
        'media_url' : GetDefaultImageUrl(user),
    })
    return HttpResponseRedirect('/user/' + user_name + '/profilepic')